
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as todoAtctions from '../store/actions/todo.actions'
import {getIn} from 'immutable'
class Header extends Component{
  addTodo = (ev)=>{
    if(ev.keyCode === 13){
      // 获取当前内容
      let taskName = ev.target.value
      if(taskName.trim().length === 0){
        alert('请输入任务名称')
        return
      }
      // 触发新增任务的指令
      this.props.add_todo(taskName)
      // 清空文本框
      ev.target.value = ''
    }
  }
  render(){
    return (
      <header className="header">
        <h1>todos</h1>
        <input 
          className={'new-todo'} 
          placeholder='还有什么任务没完成' 
          autoFocus 
          onKeyUp = {this.addTodo}
        />
      </header>
    )
  }
}

// 组件与store
const mapStateToProps = (state)=>({
  todos:getIn(state.todoReducer,['todos'])
})
// 组件与dispacth
const mapDispatchToProps = (dispatch)=>({
  ...bindActionCreators(todoAtctions,dispatch)
})


export default connect(mapStateToProps,mapDispatchToProps)(Header)